package com.his_voice.voice.utils;

import com.his_voice.voice.server.MyWebSocketClient;
import com.his_voice.voice.server.MyWebSocketServer;
import org.java_websocket.drafts.Draft_6455;
import org.java_websocket.handshake.ServerHandshake;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.net.*;
import java.util.concurrent.CountDownLatch;

@Component
public class WebSocketMapUtils {
    public static Logger log = LoggerFactory.getLogger(WebSocketMapUtils.class);

    private static final String APPID = "";

    // appid对应的secret_key
    private static final String SECRET_KEY = "";

    // 请求地址
    private static final String HOST = "rtasr.xfyun.cn/v1/ws";

    private static final String BASE_URL = "wss://" + HOST;

    private static final String ORIGIN = "https://" + HOST;

    /**
     * 一个时间戳字符串的方法
     */
    private static String getTs() {
        String ts = "";
        String time = System.currentTimeMillis() + "";
        ts = "0" + time.substring(time.length() - 3);
        return ts;
    }

    private static String baseString = APPID + getTs();


    // 生成握手参数
    public static String getHandShakeParams(String appId, String secretKey) {
        String ts = System.currentTimeMillis() / 1000 + "";
        String signa = "";
        try {
            signa = EncryptUtil.HmacSHA1Encrypt(EncryptUtil.MD5(appId + ts), secretKey);
            return "?appid=" + appId + "&ts=" + ts + "&signa=" + URLEncoder.encode(signa, "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "";
    }


    /**
     * 获取客户端连接实例
     *
     * @param url
     * @return
     */
    public static MyWebSocketClient getClient(String sessionId) throws Exception {

        URI url = new URI(BASE_URL + getHandShakeParams(APPID, SECRET_KEY));
        DraftWithOrigin draft = new DraftWithOrigin(ORIGIN);
        CountDownLatch handshakeSuccess = new CountDownLatch(1);
        CountDownLatch connectClose = new CountDownLatch(1);
        try {

            //创建客户端连接对象
            MyWebSocketClient client = new MyWebSocketClient(url, new Draft_6455()) {

                /**
                 * 建立连接调用
                 * @param serverHandshake
                 */
                @Override
                public void onOpen(ServerHandshake serverHandshake) {
                    log.info("建立连接");
                }

                /**
                 * 收到服务端消息调用
                 * @param s
                 */
                @Override
                public void onMessage(String s) {
                    log.info("处理结束返回消息:" + s);
                    System.out.println(s);
                    String msg = getExcptMessage();

                    //接收第三方websocket服务发送数据
                    System.out.println("服务端我返回消息" + s);
                }

                /**
                 * 断开连接调用
                 * @param i
                 * @param s
                 * @param b
                 */
                @Override
                public void onClose(int i, String s, boolean b) {
                    log.info("关闭连接:::" + "i = " + i + ":::s = " + s + ":::b = " + b);
                }

                /**
                 * 连接报错调用
                 * @param e
                 */
                @Override
                public void onError(Exception e) {
                    log.error("报错了:::" + e.getMessage());
                }

                @Override
                public String getExcptMessage() {
                    return super.getExcptMessage();
                }
            };
            //请求与服务端建立连接
            client.connect();
            //判断连接状态，0为请求中  1为已建立  其它值都是建立失败
            while (client.getReadyState().ordinal() == 0) {
                try {
                    Thread.sleep(200);
                } catch (Exception e) {
                    log.warn("延迟操作出现问题，但并不影响功能");
                }
                log.info("连接中。。。");
                break;
            }
            //连接状态不再是0请求中，判断建立结果是不是1已建立
            if (client.getReadyState().ordinal() == 1) {
                return client;
            }
        } catch (Exception e) {

            log.error(e.getMessage());
        }
        return null;
    }

}
